import {
  LockOutlined,
  UserOutlined,
} from '@ant-design/icons';
import { Button } from 'antd';
import {
  LoginForm,
  ProFormText,
  ProFormSelect,
} from '@ant-design/pro-components';
import { useModel } from "@@/exports";
import { request } from 'umi';
import Cookies from 'js-cookie'
import { history } from 'umi';
import { message, Space, Typography } from 'antd';
import { LoginAPI } from "@/services/LoginApi";
import { layout } from "@/app";
import { getUserInfo } from "@/utils/format";
import routes_province from "../../../../config/routes_province";
import routes_xk from "../../../../config/routes_xk";
import routes_school from "../../../../config/routes_school";
import * as url from "url";
import './index.less'
import { ShowError } from "@/utils/format";
import { fontSize } from "html2canvas/dist/types/css/property-descriptors/font-size";
export default () => {
  //判断是否登录
  try {
    const userInfo = JSON.parse(Cookies.get('userInfo'))
    if (userInfo.token) {
      location.replace('/home');
      return
    }
  } catch { }

  const handleSubmit = async (values) => {
    const queryString = new URLSearchParams(values).toString()
    console.log("@开始登录 发送数据!", queryString)

    const now = new Date();

    var try_login_count_str = Cookies.get('try_login_count')
    var last_try_login_date_str = Cookies.get('last_try_login_date')
    var last_try_login_date
    var try_login_count

    if (try_login_count_str === undefined) {
      try_login_count = 0;
    } else {
      try_login_count = parseInt(try_login_count_str);
    }

    if (last_try_login_date_str !== undefined) {
      last_try_login_date = new Date(last_try_login_date_str);
    } else {
      last_try_login_date = new Date()
    }

    if (try_login_count >= 5) {
      const hoursDifference = (now.getTime() - last_try_login_date.getTime()) / (1000 * 60 * 60);

      // 检查时间差是否大于一小时
      if (hoursDifference < 1) {
        var minutes = Math.floor((1000 * 60 * 60 - now.getTime() + last_try_login_date.getTime()) / 1000 / 60)
        ShowError("多次密码错误，请等待" + minutes + "分钟后再登录！")
        return
      }
    }

    Cookies.set('try_login_count', (try_login_count + 1).toString())
    Cookies.set('last_try_login_date', now.toString())

    const req = await LoginAPI(queryString)
    console.log('@返回数据:', req)
    if (req.token) {
      Cookies.set('userInfo', JSON.stringify(req))
      message.success('登录成功，欢迎您!')
      // location.reload()

      Cookies.set('try_login_count', "0".toString())

      const userInfo = getUserInfo()
      if (userInfo.role === "省厅管理员") {
        location.replace('/home')
      } else if (userInfo.role === "学科填报用户") {
        location.replace('/disci-cons/progress')
      } else {
        location.replace('/home')
      }
    } else {
      ShowError(req.message)
    }
  };

  return (
    <div className={'bg'}>
      <div className={'box'}>
        <div className={'lg-title'}>江西省双一流建设信息管理平台</div>
        <div className={'login'} >
          <LoginForm
            title={<div style={{ textAlign: 'left', fontFamily: '楷体', fontSize: '30px' }}>用户登录</div>}
            // subTitle={<Typography.Text>江西省双一流建设信息管理平台</Typography.Text>}
            onFinish={async (values) => {
              await handleSubmit(values);
            }}
            actions={
              <Space direction="vertical">
                <a rel="noreferrer" href='https://basic.jxeduyun.com/sso-oauth/authorize?appkey=31c478105f364af3ba5c1f0346cbcebf&redirectUri=http://syl.jiangxi.ncu.edu.cn/user/auth2Login&state=1' style={{ fontSize: 16, background: '#1890ff', color: 'white', width: '100%', height: '40px', display: 'block', textAlign: 'center', lineHeight: '40px' }}>智慧教育平台登录</a>
                <span style={{ fontSize: 13, color: '#666', lineHeight: '20px' }}>
                  学校以及学科用户请联系人工为您开通账号，且代表您已阅读并同意相关用户服务协议、隐私政策。</span>
              </Space>
            }
          >
            <>
              <div className={'lg-input'}>
                <div className={'user'}>
                  <ProFormText
                    name="username"
                    fieldProps={{
                      size: 'large',
                      prefix: <UserOutlined className={'prefixIcon'} />,

                    }}
                    placeholder={'请输入用户名'}
                    rules={[
                      {
                        required: true,
                        message: '请输入用户名!',
                      },
                    ]}
                  />
                </div>
                <div className={'psw'}>
                  <ProFormText.Password style={{ marginTop: '20px' }}
                    name="password"
                    fieldProps={{
                      size: 'large',
                      prefix: <LockOutlined className={'prefixIcon'} />,
                    }}
                    placeholder={'请输入密码'}
                    rules={[
                      {
                        required: true,
                        message: '请输入密码！',
                      },
                    ]}
                  />
                </div>
              </div>
            </>
            <div
              style={{
                marginBottom: 24,
              }}
            >
            </div>
          </LoginForm>
        </div>
      </div>
    </div>
  );
};
